package cn.idu.jvmtest;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * volatile关键字无法保证复合操作的原子性
 */
public class P2_03_PlusTask {

    public static Integer i = 0;
    static Lock lock = new ReentrantLock();
    static P2_03_PlusTask obj = new P2_03_PlusTask();

    static synchronized void increase() {
        i++;

        System.out.println(System.identityHashCode(i));
    }

    static class PlusThread implements Runnable {
        @Override
        public void run() {
            for (int j = 0; j < 10000; j++) {
                increase();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Thread[] threads = new Thread[10];

        for (int j = 0; j < 10; j++) {
            threads[j] = new Thread(new PlusThread());
            threads[j].start();
        }

        for (int j = 0; j < 10; j++) {
            threads[j].join();
        }
        System.out.println("i: " + i);

    }

}
